package com.laomuji.android.mvvm.demo.multiple

import android.widget.RadioButton
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.laomuji.android.mvvm.base.BaseActivity
import com.laomuji.android.mvvm.base.BaseActivityViewModel
import com.laomuji.android.mvvm.base.BaseFragment
import com.laomuji.android.mvvm.databinding.ActivityMultipleFragmentBinding


/**
 * 多个Fragment切换
 * @author laomuji666
 * @since 2024/2/20
 */
class MultipleFragmentActivity : BaseActivity<ActivityMultipleFragmentBinding, BaseActivityViewModel>() {
    private val fragments = ArrayList<BaseFragment<*, *>>()
    override fun initView() {
        initSwitchNav()
    }

    override fun initData() {

    }

    private fun initSwitchNav() {
        //添加Fragment
        fragments.clear()
        fragments.add(MultipleOneFragment())
        fragments.add(MultipleTwoFragment())

        //是否允许滑动
        viewBinding.vpContent.isUserInputEnabled = true
        //预加载的item个数,也就是触发Create的个数
        viewBinding.vpContent.offscreenPageLimit = fragments.size
        //设置Fragment适配器,只处理当前fragment的生命周期
        viewBinding.vpContent.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = fragments.size
            override fun createFragment(position: Int): Fragment = fragments[position]
        }
        //ViewPage2改变选中item后也改变底部导航栏的选中项
        viewBinding.vpContent.registerOnPageChangeCallback(object:ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                (viewBinding.rgNav.getChildAt(position) as RadioButton).isChecked = true
            }
        })
        //底部导航栏选中修改后也修改ViewPage2的item
        viewBinding.rgNav.setOnCheckedChangeListener{group, checkedId->
            for (i in 0 until group.childCount) {
                if (group.getChildAt(i).id == checkedId) {
                    viewBinding.vpContent.setCurrentItem(i, false)
                    return@setOnCheckedChangeListener
                }
            }
        }
    }


}